package com.aj.http;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import android.content.Context;
import android.util.Log;

import com.aj.activity.R;
import com.aj.sharepreferences.LoveHomeSharedPreferences;
import com.aj.utils.MobileUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.entity.ByteArrayEntity;
import cz.msebera.android.httpclient.entity.StringEntity;
import cz.msebera.android.httpclient.entity.mime.MultipartEntityBuilder;
import cz.msebera.android.httpclient.entity.mime.content.FileBody;

public class AsynchronizationHttpRequest {
	private static final String TAG = AsynchronizationHttpRequest.class
			.getName();

	private static final String CLIENTERROR_STRING = "{\"returnCode\":\"0x99999\",\"serviceName\":\"clent_error\",\"result\":\",errorMsg\":\"%s\"}";
	private static final String WIFIRROR_STRING = "{\"returnCode\":999998,\"serviceName\":\"clent_error\",\"result\":\"\",errorMsg\":\"%s\"}";

	private static final int SUCCESS_CODE_INT = 200;

	public interface IHttpCallBack {
		public void success(String result);

		public void fail(String result);
	}

	public AsynchronizationHttpRequest() {

	}

	public void excute(Context context, String url,
			HashMap<String, String> paramsMap, IHttpCallBack httpCallBack) {
		excute(context, url, paramsMap, httpCallBack, false);
	}

	public void excute(Context context, String url,
			HashMap<String, String> paramsMap,
			final IHttpCallBack httpCallBack, boolean isNeedJudgeWifiFlag) {
		RequestParams params = new RequestParams(paramsMap);
		Log.e(TAG, "http request url:" + url);

		if (isNeedJudgeWifiFlag) {
			if (LoveHomeSharedPreferences.getWifiFlag()
					&& !MobileUtil.isWifiConnect(context)) {
				return;
			}
		}

		HttpUtils.asyncPost(url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {
				if (httpCallBack != null) {
					try {
						if (statusCode == SUCCESS_CODE_INT) {
							httpCallBack.success(new String(responseBody,
									DEFAULT_CHARSET));
						} else {
							httpCallBack.fail(String
									.format(CLIENTERROR_STRING,
											TAG
													+ " error from : Request Error ,statusCode:"
													+ statusCode));
						}
					} catch (UnsupportedEncodingException e) {
						httpCallBack.fail(String.format(CLIENTERROR_STRING, TAG
								+ " error from : UnsupportedEncodingException:"
								+ e.getLocalizedMessage()));
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				if (httpCallBack != null) {
					try {
						httpCallBack.fail(String.format(
								CLIENTERROR_STRING,
								TAG
										+ " Http Error:"
										+ new String(responseBody,
												DEFAULT_CHARSET)
										+ "  error message:"
										+ error.getLocalizedMessage()));
					} catch (UnsupportedEncodingException e) {
						httpCallBack.fail(String.format(CLIENTERROR_STRING, TAG
								+ " error from : UnsupportedEncodingException:"
								+ e.getLocalizedMessage()));
					}
				}
			}

			@Override
			public void onFinish() {
				super.onFinish();
			}
		});
	}

	public void excute(Context context, String url, String paramsString,
			final IHttpCallBack httpCallBack) {
		excute(context, url, paramsString, httpCallBack, false);
	}

	public void excuteSync(Context context, String url, String paramsString,
			final IHttpCallBack httpCallBack) {
		excuteSync(context, url, paramsString, httpCallBack, false);
	}

	public void excuteSync(Context context, String url, String paramsString,
			final IHttpCallBack httpCallBack, boolean isNeedJudgeWifiFlag) {
		Log.e(TAG, "http request url:" + url);
		if (isNeedJudgeWifiFlag) {
			if (LoveHomeSharedPreferences.getWifiFlag()
					&& !MobileUtil.isWifiConnect(context)) {
				httpCallBack.fail(String.format(WIFIRROR_STRING, context
						.getResources().getString(R.string.wifi_error_text)));
				return;
			}
		}
		StringEntity stringEntity;
		try {
			stringEntity = new StringEntity(paramsString, "UTF-8");
			HttpUtils.syncPost(context, url, stringEntity, "application/json",
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int statusCode, Header[] headers,
								byte[] responseBody) {
							try {
								Log.e(TAG, "responseBody:"
										+ new String(responseBody,
												DEFAULT_CHARSET));
							} catch (Exception e1) {
								httpCallBack.fail(String.format(
										CLIENTERROR_STRING, TAG
												+ " error from :Exception:"
												+ e1.getLocalizedMessage()));
							}
							if (httpCallBack != null) {
								try {
									if (statusCode == SUCCESS_CODE_INT) {
										httpCallBack.success(new String(
												responseBody, DEFAULT_CHARSET));
									} else {
										httpCallBack.fail(String
												.format(CLIENTERROR_STRING,
														TAG
																+ " error from : Request Error ,statusCode:"
																+ statusCode));
									}
								} catch (UnsupportedEncodingException e) {
									httpCallBack.fail(String
											.format(CLIENTERROR_STRING,
													TAG
															+ " error from : UnsupportedEncodingException:"
															+ e.getLocalizedMessage()));
									e.printStackTrace();
								}
							}
						}

						@Override
						public void onFailure(int statusCode, Header[] headers,
								byte[] responseBody, Throwable error) {
							if (responseBody == null) {
								httpCallBack.fail(String.format(
										CLIENTERROR_STRING, TAG
												+ " responseBody is Null"));
								return;
							}

							try {
								Log.e(TAG, "fail responseBody:"
										+ new String(responseBody,
												DEFAULT_CHARSET));
							} catch (Exception e1) {
								httpCallBack.fail(String.format(
										CLIENTERROR_STRING, TAG
												+ " error from :Exception:"
												+ e1.getLocalizedMessage()));
							}
							if (httpCallBack != null) {
								try {
									httpCallBack.fail(String.format(
											CLIENTERROR_STRING,
											TAG
													+ " Http Error:"
													+ new String(responseBody,
															DEFAULT_CHARSET)
													+ "  error message:"
													+ error.getLocalizedMessage()));
								} catch (UnsupportedEncodingException e) {
									httpCallBack.fail(String
											.format(CLIENTERROR_STRING,
													TAG
															+ " error from : UnsupportedEncodingException:"
															+ e.getLocalizedMessage()));
								}
							}
						}

						@Override
						public void onFinish() {
							super.onFinish();
						}
					});
		} catch (Exception e1) {
			httpCallBack.fail(String.format(CLIENTERROR_STRING, TAG
					+ " error from :Exception:" + e1.getLocalizedMessage()));
		}
	}

	public void excute(Context context, String url, String paramsString,
			final IHttpCallBack httpCallBack, boolean isNeedJudgeWifiFlag) {
		Log.e(TAG, "http request url:" + url);
		if (isNeedJudgeWifiFlag) {
			if (LoveHomeSharedPreferences.getWifiFlag()
					&& !MobileUtil.isWifiConnect(context)) {
				httpCallBack.fail(String.format(WIFIRROR_STRING, context
						.getResources().getString(R.string.wifi_error_text)));
				return;
			}
		}
		StringEntity stringEntity;
		try {
			stringEntity = new StringEntity(paramsString, "UTF-8");
			HttpUtils.asyncPost(context, url, stringEntity, "application/json",
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int statusCode, Header[] headers,
								byte[] responseBody) {
							try {
								Log.e(TAG, "responseBody:"
										+ new String(responseBody,
												DEFAULT_CHARSET));
							} catch (Exception e1) {
								httpCallBack.fail(String.format(
										CLIENTERROR_STRING, TAG
												+ " error from :Exception:"
												+ e1.getLocalizedMessage()));
							}
							if (httpCallBack != null) {
								try {
									if (statusCode == SUCCESS_CODE_INT) {
										httpCallBack.success(new String(
												responseBody, DEFAULT_CHARSET));
									} else {
										httpCallBack.fail(String
												.format(CLIENTERROR_STRING,
														TAG
																+ " error from : Request Error ,statusCode:"
																+ statusCode));
									}
								} catch (UnsupportedEncodingException e) {
									httpCallBack.fail(String
											.format(CLIENTERROR_STRING,
													TAG
															+ " error from : UnsupportedEncodingException:"
															+ e.getLocalizedMessage()));
									e.printStackTrace();
								}
							}
						}

						@Override
						public void onFailure(int statusCode, Header[] headers,
								byte[] responseBody, Throwable error) {
							if (responseBody == null) {
								httpCallBack.fail(String.format(
										CLIENTERROR_STRING, TAG
												+ " responseBody is Null"));
								return;
							}

							try {
								Log.e(TAG, "fail responseBody:"
										+ new String(responseBody,
												DEFAULT_CHARSET));
							} catch (Exception e1) {
								httpCallBack.fail(String.format(
										CLIENTERROR_STRING, TAG
												+ " error from :Exception:"
												+ e1.getLocalizedMessage()));
							}
							if (httpCallBack != null) {
								try {
									httpCallBack.fail(String.format(
											CLIENTERROR_STRING,
											TAG
													+ " Http Error:"
													+ new String(responseBody,
															DEFAULT_CHARSET)
													+ "  error message:"
													+ error.getLocalizedMessage()));
								} catch (UnsupportedEncodingException e) {
									httpCallBack.fail(String
											.format(CLIENTERROR_STRING,
													TAG
															+ " error from : UnsupportedEncodingException:"
															+ e.getLocalizedMessage()));
								}
							}
						}

						@Override
						public void onFinish() {
							super.onFinish();
						}
					});
		} catch (Exception e1) {
			httpCallBack.fail(String.format(CLIENTERROR_STRING, TAG
					+ " error from :Exception:" + e1.getLocalizedMessage()));
		}
	}

	public void excuteByte(Context context, String url, String paramsString,
			byte[] byteArray, final IHttpCallBack httpCallBack) {
		excuteByte(context, url, paramsString, byteArray, httpCallBack, false);
	}

	public void excuteByte(Context context, String url, String paramsString,
			byte[] byteArray, final IHttpCallBack httpCallBack,
			boolean isNeedJudgeWifiFlag) {

		if (isNeedJudgeWifiFlag) {
			if (LoveHomeSharedPreferences.getWifiFlag()
					&& !MobileUtil.isWifiConnect(context)) {
				httpCallBack.fail(String.format(WIFIRROR_STRING, context
						.getResources().getString(R.string.wifi_error_text)));
				return;
			}
		}
		ByteArrayEntity byteArrayEntity;
		try {
			// url += "&jsonParams=" + paramsString;
			Log.e(TAG, "http request url:" + url);
			byteArrayEntity = new ByteArrayEntity(byteArray);
			// MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			// builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			// builder.setCharset(Charset.forName("UTF-8"));
			// HttpEntity httpeEntity = builder.addBinaryBody("file",
			// byteArrayEntity).build();
			HttpUtils.asyncPost(context, url, byteArrayEntity,
					"application/octet-stream", new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int statusCode, Header[] headers,
								byte[] responseBody) {
							try {
								Log.e(TAG, "responseBody:"
										+ new String(responseBody,
												DEFAULT_CHARSET));
							} catch (UnsupportedEncodingException e1) {
								e1.printStackTrace();
							}
							if (httpCallBack != null) {
								try {
									if (statusCode == SUCCESS_CODE_INT) {
										httpCallBack.success(new String(
												responseBody, DEFAULT_CHARSET));
									} else {
										httpCallBack.fail(String
												.format(CLIENTERROR_STRING,
														TAG
																+ " error from : Request Error ,statusCode:"
																+ statusCode));
									}
								} catch (UnsupportedEncodingException e) {
									httpCallBack.fail(String
											.format(CLIENTERROR_STRING,
													TAG
															+ " error from : UnsupportedEncodingException:"
															+ e.getLocalizedMessage()));
									e.printStackTrace();
								}
							}
						}

						@Override
						public void onFailure(int statusCode, Header[] headers,
								byte[] responseBody, Throwable error) {
							try {
								Log.e(TAG, "responseBody error:"
										+ new String(responseBody,
												DEFAULT_CHARSET), error);
							} catch (UnsupportedEncodingException e1) {
								e1.printStackTrace();
							}
							if (httpCallBack != null) {
								try {
									httpCallBack.fail(String.format(
											CLIENTERROR_STRING,
											TAG
													+ " Http Error:"
													+ new String(responseBody,
															DEFAULT_CHARSET)
													+ "  error message:"
													+ error.getLocalizedMessage()));
								} catch (UnsupportedEncodingException e) {
									httpCallBack.fail(String
											.format(CLIENTERROR_STRING,
													TAG
															+ " error from : UnsupportedEncodingException:"
															+ e.getLocalizedMessage()));
								}
							}
						}

						@Override
						public void onFinish() {
							super.onFinish();
						}
					});
		} catch (Exception e1) {
			httpCallBack.fail(String.format(CLIENTERROR_STRING, TAG
					+ " error from :Exception:" + e1.getLocalizedMessage()));
		}
	}

	public void excuteFile(Context context, String url, String paramsString,
			File file, final IHttpCallBack httpCallBack) {
		excuteFile(context, url, paramsString, file, httpCallBack, false);
	}

	public void excuteSynFile(Context context, String url, String paramsString,
			File file, final IHttpCallBack httpCallBack) {
		excuteSynFile(context, url, paramsString, file, httpCallBack, false);
	}

	public void excuteSynFile(Context context, String url, String paramsString,
			File file, final IHttpCallBack httpCallBack,
			boolean isNeedJudgeWifiFlag) {

		if (isNeedJudgeWifiFlag) {
			if (LoveHomeSharedPreferences.getWifiFlag()
					&& !MobileUtil.isWifiConnect(context)) {
				httpCallBack.fail(String.format(WIFIRROR_STRING, context
						.getResources().getString(R.string.wifi_error_text)));
				return;
			}
		}
		try {
			Log.e(TAG, "http request url:" + url);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			HttpEntity httpeEntity = builder
					.addPart("file", new FileBody(file)).build();
			RequestParams params = new RequestParams();
			params.put("file", file, "application/octet-stream",
					System.currentTimeMillis() + ".jpg");
			HttpUtils.syncPost(url, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						byte[] responseBody) {
					try {
						Log.e(TAG, "responseBody:"
								+ new String(responseBody, DEFAULT_CHARSET));
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					}
					if (httpCallBack != null) {
						try {
							if (statusCode == SUCCESS_CODE_INT) {
								httpCallBack.success(new String(responseBody,
										DEFAULT_CHARSET));
							} else {
								httpCallBack.fail(String
										.format(CLIENTERROR_STRING,
												TAG
														+ " error from : Request Error ,statusCode:"
														+ statusCode));
							}
						} catch (UnsupportedEncodingException e) {
							httpCallBack.fail(String
									.format(CLIENTERROR_STRING,
											TAG
													+ " error from : UnsupportedEncodingException:"
													+ e.getLocalizedMessage()));
							e.printStackTrace();
						}
					}
				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable error) {
					try {
						Log.e(TAG, "responseBody error:"
								+ new String(responseBody, DEFAULT_CHARSET),
								error);
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					}
					if (httpCallBack != null) {
						try {
							httpCallBack.fail(String.format(
									CLIENTERROR_STRING,
									TAG
											+ " Http Error:"
											+ new String(responseBody,
													DEFAULT_CHARSET)
											+ "  error message:"
											+ error.getLocalizedMessage()));
						} catch (UnsupportedEncodingException e) {
							httpCallBack.fail(String
									.format(CLIENTERROR_STRING,
											TAG
													+ " error from : UnsupportedEncodingException:"
													+ e.getLocalizedMessage()));
						}
					}
				}

				@Override
				public void onFinish() {
					super.onFinish();
				}
			});
		} catch (Exception e1) {
			Log.e(TAG, "", e1);
			httpCallBack.fail(String.format(CLIENTERROR_STRING, TAG
					+ " error from :Exception:" + e1.getLocalizedMessage()));
		}
	}

	public void excuteFile(Context context, String url, String paramsString,
			File file, final IHttpCallBack httpCallBack,
			boolean isNeedJudgeWifiFlag) {

		if (isNeedJudgeWifiFlag) {
			if (LoveHomeSharedPreferences.getWifiFlag()
					&& !MobileUtil.isWifiConnect(context)) {
				httpCallBack.fail(String.format(WIFIRROR_STRING, context
						.getResources().getString(R.string.wifi_error_text)));
				return;
			}
		}
		try {
			// url += "&jsonParams=" + paramsString;
			Log.e(TAG, "http request url:" + url);
			// FileEntity fileEntity = new FileEntity(file);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			// // builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			// // builder.setCharset(Charset.forName("UTF-8"));
			HttpEntity httpeEntity = builder
					.addPart("file", new FileBody(file)).build();
			RequestParams params = new RequestParams();
			params.put("file", file, "application/octet-stream",
					System.currentTimeMillis() + ".jpg");
			// RequestParams params = new RequestParams("file", new
			// FileBody(file));
			// multipart/form-data
			/**
			 * HttpUtils.asyncPost(context, url, httpeEntity,
			 * "application/octet-stream", new AsyncHttpResponseHandler()
			 */
			HttpUtils.asyncPost(url, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						byte[] responseBody) {
					try {
						Log.e(TAG, "responseBody:"
								+ new String(responseBody, DEFAULT_CHARSET));
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					}
					if (httpCallBack != null) {
						try {
							if (statusCode == SUCCESS_CODE_INT) {
								httpCallBack.success(new String(responseBody,
										DEFAULT_CHARSET));
							} else {
								httpCallBack.fail(String
										.format(CLIENTERROR_STRING,
												TAG
														+ " error from : Request Error ,statusCode:"
														+ statusCode));
							}
						} catch (UnsupportedEncodingException e) {
							httpCallBack.fail(String
									.format(CLIENTERROR_STRING,
											TAG
													+ " error from : UnsupportedEncodingException:"
													+ e.getLocalizedMessage()));
							e.printStackTrace();
						}
					}
				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable error) {
					try {
						Log.e(TAG, "responseBody error:"
								+ new String(responseBody, DEFAULT_CHARSET),
								error);
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					}
					if (httpCallBack != null) {
						try {
							httpCallBack.fail(String.format(
									CLIENTERROR_STRING,
									TAG
											+ " Http Error:"
											+ new String(responseBody,
													DEFAULT_CHARSET)
											+ "  error message:"
											+ error.getLocalizedMessage()));
						} catch (UnsupportedEncodingException e) {
							httpCallBack.fail(String
									.format(CLIENTERROR_STRING,
											TAG
													+ " error from : UnsupportedEncodingException:"
													+ e.getLocalizedMessage()));
						}
					}
				}

				@Override
				public void onFinish() {
					super.onFinish();
				}
			});
		} catch (Exception e1) {
			Log.e(TAG, "", e1);
			httpCallBack.fail(String.format(CLIENTERROR_STRING, TAG
					+ " error from :Exception:" + e1.getLocalizedMessage()));
		}
	}
}
